package com.ruoyi.student.service;

import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.student.domain.StudentBaodao;
import com.ruoyi.student.domain.StudentInfo;
import com.ruoyi.student.domain.StudentInfoImport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import jakarta.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

@Service
public class StudentImportAsyncService {

    @Autowired
    private IStudentBaodaoService studentBaodaoService;

    @Autowired
    private IStudentInfoService studentInfoService;

    @Autowired
    private IStudentInfoImportService studentInfoImportService;

    // 存储导入进度的线程安全Map
    private final Map<String, ImportProgress> importProgressMap = new ConcurrentHashMap<>();

    /**
     * 异步执行批量导入（仅处理typeStatus为"1"的报到记录）
     */
    @Async
    @Transactional(rollbackFor = Exception.class)
    public Future<ImportResult> doImport(String batchNo) {
        // 初始化进度信息
        ImportProgress progress = new ImportProgress();
        progress.setBatchNo(batchNo);
        progress.setStatus("处理中");
        progress.setProgress(0);
        importProgressMap.put(batchNo, progress);

        try {
            // 1. 查询所有报到学生，过滤出typeStatus为"1"的记录
            List<StudentBaodao> studentBaodaoList = studentBaodaoService.selectStudentBaodaoList(new StudentBaodao());
            // 核心修改：只保留typeStatus为"1"的记录（处理可能为null的情况）
            System.out.println(studentBaodaoList);
            studentBaodaoList = studentBaodaoList.stream()
                    .filter(baodao -> Objects.equals(baodao.getTypeStatus(), "1")
                            && Objects.equals(baodao.getShuoshiboshi(), "1")) // 新增硕士类型过滤
                    .collect(Collectors.toList());

            int total = studentBaodaoList.size();
            progress.setTotal(total);
            importProgressMap.put(batchNo, progress);


            if (total == 0) {
                progress.setStatus("完成");
                progress.setProgress(100);
                return new AsyncResult<>(new ImportResult(batchNo, 0, "无typeStatus为1的报到数据需要导入"));
            }

            // 2. 批量查询已存在的学生ID（使用Set提高查询效率）
            List<StudentInfo> existingStudents = studentInfoService.getAllStudentInfoList(new StudentInfo());
            Set<String> existingStudentIds = existingStudents.stream()
                    .filter(s -> s.getStudentId() != null)
                    .map(StudentInfo::getStudentId)
                    .collect(Collectors.toSet());

            // 3. 收集需要查询的学号，批量获取StudentInfoImport数据
            Set<String> needQueryXh = studentBaodaoList.stream()
                    .map(StudentBaodao::getStudentNum)
                    .filter(xh -> !existingStudentIds.contains(xh))
                    .collect(Collectors.toSet());

            // 批量查询并转为Map（xh -> StudentInfoImport）
            Map<String, StudentInfoImport> xhToImportMap = new HashMap<>();
            if (!needQueryXh.isEmpty()) {
                StudentInfoImport query = new StudentInfoImport();
                query.setXhList(new ArrayList<>(needQueryXh));
                List<StudentInfoImport> importList = studentInfoImportService.selectBatchByXh(query);

                for (StudentInfoImport importData : importList) {
                    String xh = importData.getXh();
                    if (xhToImportMap.containsKey(xh)) {
                        throw new RuntimeException("学号" + xh + "存在多条导入数据，请检查");
                    }
                    xhToImportMap.put(xh, importData);
                }
            }

            // 4. 构建批量插入列表
            List<StudentInfo> insertList = new ArrayList<>(100);
            int successCount = 0;

            for (int i = 0; i < studentBaodaoList.size(); i++) {
                StudentBaodao baodao = studentBaodaoList.get(i);
                String studentNum = baodao.getStudentNum();

                // 跳过已存在的学生
                if (existingStudentIds.contains(studentNum)) {
                    updateProgress(progress, i + 1, total, successCount);
                    continue;
                }

                // 校验导入数据是否存在
                StudentInfoImport importData = xhToImportMap.get(studentNum);
                if (importData == null) {
                    throw new RuntimeException("学号" + studentNum + "未找到对应导入数据");
                }

                // 构建学生信息
                StudentInfo studentInfo = new StudentInfo();
                studentInfo.setId(IdUtils.fastSimpleUUID());
                studentInfo.setStudentId(importData.getXh());//学号
                studentInfo.setStudentName(importData.getXm());//姓名
                studentInfo.setStudentZy(importData.getLqzydm());//专业*
                studentInfo.setStudentYx(importData.getLqyxsm());//院系*
                studentInfo.setStudentNation(importData.getMzm());//民族*
                studentInfo.setStudentRegion("中华人民共和国");//国家地区
                studentInfo.setStudentHk(importData.getHkszdm());//户口
                studentInfo.setStudentHkxxdz(importData.getHkszdxxdz());//户口详细地址
                studentInfo.setStudentCtype(importData.getZjlx());//证件类型*
                studentInfo.setStudentCnum(importData.getZjhm());//证件号码*
                studentInfo.setStudentSex(importData.getXbm());//性别*
                studentInfo.setStudentXz(importData.getXz());//学制

                // 安全处理学号截取（避免越界）
                String xh = importData.getXh();
                if (xh != null && xh.length() >= 9) {
                    studentInfo.setStudentNj(xh.substring(5, 9));
                } else {
                    studentInfo.setStudentNj("");
                }

                studentInfo.setStudentBydw(importData.getBydw());//毕业单位
                studentInfo.setStudentByzy(importData.getByzymc());//毕业专业
                studentInfo.setStudentByzym(importData.getByzydm());//毕业专业码
                studentInfo.setStudentYjfxm(importData.getLqyjfxdm());//研究方向码
                studentInfo.setStudentYjfx(importData.getLqyjfxmc());//研究方向
                studentInfo.setBirthday(importData.getCsrq());// 出生日期
                studentInfo.setStudentPa(importData.getZzmmm());//政治面貌
                studentInfo.setStudentMarr(importData.getHfm());//婚姻码
                studentInfo.setStudentSjby(importData.getByny());//毕业年月
                studentInfo.setStudentZxjh(importData.getZxjh());//专项计划
                studentInfo.setStudentXxfs(importData.getLqxxfs());//学习方式**
                studentInfo.setStudentDadz(importData.getDaszdwdz());//档案地址
                studentInfo.setStudentDadzyzbm(importData.getDaszdwyzbm());//档案地址邮政编码
                studentInfo.setStudentXwzh(importData.getXwzsbh());//学位证书编号
                studentInfo.setKsfs(importData.getKsfsm());//考试方式
                studentInfo.setBeizhu(importData.getBz());//备注
                studentInfo.setStudentDxjydw(importData.getDxwpdw());//定向就业单位
                studentInfo.setStudentLqpydw(importData.getLhpydw());//录取培养单位
                studentInfo.setStudentLqpydwm(importData.getLhpydwm());//录取培养单位吗
                studentInfo.setStudentSjh(importData.getLxfs());//联系方式
                studentInfo.setStudentRwsj(importData.getRwny());//入伍时间
                studentInfo.setStudentTysj(importData.getTyny());//退役时间
                studentInfo.setStudentPzrujgmc(importData.getRwpzdw());//批准入伍机关名称
                studentInfo.setStudentPztyjgmc(importData.getTypzdw());//批准退役机关名称
                studentInfo.setStudentTcxyzbh(importData.getTcxyzbh());//退出现役证编号
                studentInfo.setStudentRwqszgxmc(importData.getRwqgxmc());//入伍前所在高校名称
                studentInfo.setStudentRwqszgxxxxs(importData.getRwqxxxs());//入伍前所在高校学习形式
                studentInfo.setStudentRwqszgxxxzy(importData.getRwqzymc());//入伍前所在高校学习专业
                insertList.add(studentInfo);
                successCount++;

                // 每100条批量插入一次
                if (insertList.size() >= 100) {
                    studentInfoService.batchInsert(insertList);
                    insertList.clear();
                }

                // 更新进度
                updateProgress(progress, i + 1, total, successCount);
            }

            // 插入剩余数据
            if (!insertList.isEmpty()) {
                studentInfoService.batchInsert(insertList);
            }

            // 完成处理
            progress.setStatus("完成");
            progress.setProgress(100);
            progress.setSuccessCount(successCount);
            importProgressMap.put(batchNo, progress);

            return new AsyncResult<>(new ImportResult(batchNo, successCount, "导入成功"));

        } catch (Exception e) {
            progress.setStatus("失败");
            progress.setErrorMsg(e.getMessage());
            importProgressMap.put(batchNo, progress);
            return new AsyncResult<>(new ImportResult(batchNo, 0, "导入失败：" + e.getMessage()));
        }
    }

    /**
     * 查询导入进度
     */
    public ImportProgress getImportProgress(String batchNo) {
        return importProgressMap.getOrDefault(batchNo, new ImportProgress());
    }

    /**
     * 更新进度信息
     */
    private void updateProgress(ImportProgress progress, int current, int total, int successCount) {
        progress.setProgress((int) ((current * 1.0 / total) * 100));
        progress.setSuccessCount(successCount);
        importProgressMap.put(progress.getBatchNo(), progress);
    }

    // 导入进度内部类
    public static class ImportProgress {
        private String batchNo;
        private String status; // 处理中/完成/失败
        private int progress; // 0-100
        private int total; // 总条数
        private int successCount; // 成功条数
        private String errorMsg; // 错误信息

        // Getter和Setter
        public String getBatchNo() { return batchNo; }
        public void setBatchNo(String batchNo) { this.batchNo = batchNo; }
        public String getStatus() { return status; }
        public void setStatus(String status) { this.status = status; }
        public int getProgress() { return progress; }
        public void setProgress(int progress) { this.progress = progress; }
        public int getTotal() { return total; }
        public void setTotal(int total) { this.total = total; }
        public int getSuccessCount() { return successCount; }
        public void setSuccessCount(int successCount) { this.successCount = successCount; }
        public String getErrorMsg() { return errorMsg; }
        public void setErrorMsg(String errorMsg) { this.errorMsg = errorMsg; }
    }

    // 导入结果内部类
    public static class ImportResult {
        private String batchNo;
        private int successCount;
        private String msg;

        public ImportResult(String batchNo, int successCount, String msg) {
            this.batchNo = batchNo;
            this.successCount = successCount;
            this.msg = msg;
        }

        // Getter和Setter
        public String getBatchNo() { return batchNo; }
        public void setBatchNo(String batchNo) { this.batchNo = batchNo; }
        public int getSuccessCount() { return successCount; }
        public void setSuccessCount(int successCount) { this.successCount = successCount; }
        public String getMsg() { return msg; }
        public void setMsg(String msg) { this.msg = msg; }
    }
}
